﻿using System;
using System.Runtime.Caching;

namespace WCF.NinjectDependencyInjectionDemo.Core
{
    public interface ICache
    {
        /// <summary>
        /// Gets an item from the cache. Return default(T) if not found.
        /// </summary>
        T Get<T>(string cacheKey);

        /// <summary>
        /// Places an item into the cache.
        /// </summary>
        void Put(string cacheKey, object item);

        /// <summary>
        /// Clears an item from the cache.
        /// </summary>
        void Clear(string cacheKey);
    }

    public class Cache : ICache
    {
        private readonly ObjectCache _cache = MemoryCache.Default;

        public T Get<T>(string cacheKey)
        {
            var item = _cache[cacheKey];
            if (item == null) return default(T);
            if (item is T == false) return default(T);

            return (T)item;
        }

        public void Put(string cacheKey, object item)
        {
            _cache.Set(cacheKey, item, new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddHours(48) });
        }

        public void Clear(string cacheKey)
        {
            _cache.Remove(cacheKey);
        }
    }
}